package com.allm.ai.api.service;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.allm.ai.api.context.UserContextHolder;
import com.allm.ai.api.dto.UserInfo;

import cn.authing.sdk.java.client.ManagementClient;
import cn.authing.sdk.java.dto.GetUserDto;
import cn.authing.sdk.java.dto.UserSingleRespDto;
import lombok.extern.slf4j.Slf4j;

/**
 * 用户服务
 */
@Service
@Slf4j
public class UserService {
    
    private final ManagementClient managementClient;
    private final RedisTemplate<String, Object> redisTemplate;
    private static final String USER_CACHE_PREFIX = "user:info:";
    
    public UserService(ManagementClient managementClient, RedisTemplate<String, Object> redisTemplate) {
        this.managementClient = managementClient;
        this.redisTemplate = redisTemplate;
    }
    
    /**
     * 从 UserContextHolder 获取当前用户信息
     */
    public UserInfo getCurrentUser() {
        UserInfo userInfo = UserContextHolder.getUser();
        if (userInfo == null) {
            log.warn("当前用户信息为空");
            return null;
        }
        return userInfo;
    }
    
    /**
     * 获取当前用户ID（从 UserContextHolder）
     */
    public String getCurrentUserId() {
        UserInfo userInfo = getCurrentUser();
        return userInfo != null ? userInfo.getId() : "anonymous";
    }
    
    /**
     * 获取用户信息（带缓存）
     */
    public UserInfo getUserInfoWithCache(String userId) {
        try {
            String cacheKey = USER_CACHE_PREFIX + userId;

            // 1. 先从缓存中获取
            UserInfo cachedUser = (UserInfo)redisTemplate.opsForValue().get(cacheKey);
            if (cachedUser != null) {
                log.debug("User info cache HIT for userId: {}", userId);
                return cachedUser;
            }

            // 2. 缓存未命中，从 ManagementClient 获取
            log.debug("User info cache MISS for userId: {}. Fetching from Authing.", userId);
            GetUserDto getUserDto = new GetUserDto();
            getUserDto.setUserId(userId);
            UserSingleRespDto userSingleRespDto = managementClient.getUser(getUserDto);

            // 3. 将获取到的用户信息存入缓存
            if (userSingleRespDto != null && userSingleRespDto.getData() != null) {
                UserInfo userToCache = convertToCachedUserInfo(userSingleRespDto.getData());
                
                redisTemplate.opsForValue().set(cacheKey, userToCache);
                log.debug("User info for userId: {} populated to cache.", userId);
                
                return userToCache;
            }

        } catch (Exception e) {
            log.error("Failed to get user info for userId: {}, error: {}", userId, e.getMessage(), e);
        }
        
        return null;
    }
    
    /**
     * 将 ManagementClient 返回的用户数据转换为 CachedUserInfo
     */
    public UserInfo convertToCachedUserInfo(cn.authing.sdk.java.dto.UserDto userDto) {
        return UserInfo.builder()
                .id(userDto.getUserId())
                .username(userDto.getUsername())
                .nickname(userDto.getNickname())
                .picture(userDto.getPhoto())
                .email(userDto.getEmail())
                .phone(userDto.getPhone())
                .gender(userDto.getGender() != null ? userDto.getGender().toString() : null)
                .birthdate(userDto.getBirthdate())
                .country(userDto.getCountry())
                .province(userDto.getProvince())
                .city(userDto.getCity())
                .build();
    }

}